package com.njtoyo.taxi.admin.utils.encrypt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

@Slf4j
public class AESEncryptionUtil {

    /**
     *加密操作
     * @param content  待加密内容
     * @param encodingFormat 编码方式
     * @param sKey 密码
     * @param ivParameter 偏移量
     * @return
     * @throws Exception
     */
    public  static String encrypt(String content, String encodingFormat, String sKey, String ivParameter) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(content.getBytes(encodingFormat));
            return Base64Utils.encodeToString(encrypted);
        }catch (Exception e){
            log.error("data {} encrypt on error {}",content,e);
        }
        return null;
    }

    /**
     *解密操作
     * @param content 待解密内容
     * @param encodingFormat 编码方式
     * @param sKey 密码
     * @param ivParameter 偏移量
     * @return
     * @throws Exception
     */
    public String decrypt(String content, String encodingFormat, String sKey, String ivParameter) {
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] encrypted1 = Base64Utils.decodeFromString(content);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, encodingFormat);
            return originalString;
        } catch (Exception ex) {
            log.error("data {} decrypt on error {}",content,ex);
        }
        return null;
    }


    public static void main(String[] args) {
        String data="{\"cardType\":1,\"redemptionCode\":\"\",\"cardNo\":\"9030040002321534\",\"selectCity\":\"深圳\",\"fromPage\":\"yk\",\"X-PA-NONCESTR\":\"1471C8D3F-0193-4073-B9A4-C6F8375012FA\",\"X-PA-NEEDEXECUTIONID\":1}";
        System.out.println(encrypt(data,"UTF-8","0568754762754994","0568754762754994"));;
    }
}
